/**
 * @author 
 * @createtime 
 * @class StaffRecruitapplyForm
 * @extends Ext.Window
 * @description StaffRecruitapply表单
 */
StaffRecruitapplyForm=Ext.extend(Ext.Window,{
	//内嵌FormPanel
	formPanel:null,
	//构造函数
	constructor:function(_cfg){
		Ext.applyIf(this,_cfg);
		//必须先初始化组件
		this.initUIComponents();
		StaffRecruitapplyForm.superclass.constructor.call(this,{
			id:'StaffRecruitapplyFormWin',
			layout:'fit',
			items:this.formPanel,
			modal:true,
			width : 750,
			height : 370,
			maximizable:true,
			title:'[招聘]详细信息',
			buttonAlign : 'center',
			buttons:this.buttons
		});
	},//end of the constructor
	//初始化组件
	initUIComponents:function(){
		var thizId = this.id;
		this.formPanel=new Ext.FormPanel({
				layout : 'form',
				trackResetOnLoad:true,
				bodyStyle: 'padding:10px 10px 10px 10px',
				border:false,
				url : __ctxPath + '/statistics/saveStaffRecruitapply.do',
				id : 'StaffRecruitapplyForm',
				defaults : {
					anchor : '98%,98%'
				},
				defaultType : 'textfield',
				items : [{
							name : 'staffRecruitapply.id',
							id : 'id',
							xtype:'hidden',
							value : this.id == null ? '' : this.id
						},{
								xtype: 'container',
								layout:'column',
								height:25,
								defaults:{
									xtype:'label',
									style:{
										margin:'0px 0px 3px 0px'
									}
								},
								items:[
									{
										text:'申请人：',
										width:60
									},{
										xtype:'textfield',
										name:'applyUserName',
										id:'applyUserName',
										emptyText:'请选择申请人',
										allowBlank:false,
										width:100,
										listeners:{
											focus:function(){
												UserSelector.getView(function(ids, names) {
														Ext.getCmp("applyUserName").setValue(names);
														Ext.getCmp("staffRecruitapply.applyUser.userId").setValue(ids);
														Ext.getCmp("staffRecruitapply.dept.depId").setValue('');
														Ext.getCmp("applyDepName").setValue('');
														if(!Ext.isEmpty(ids)){
															Ext.Ajax.request({
																url : __ctxPath
																		+ "/system/getAppUser.do",
																params : {
																	userId : ids
																},
																method : "post",
																success : function(response) {
																	var e = Ext.util.JSON.decode(response.responseText).data[0];
																	Ext.getCmp("staffRecruitapply.dept.depId").setValue(e.department.depId);
																	Ext.getCmp("applyDepName").setValue(e.department.depName);
																}
															});
														}
													}, true).show();
											}
										}
									},
									{
										xtype : "hidden",
										name : "staffRecruitapply.applyUser.userId",
										id : "staffRecruitapply.applyUser.userId"
									},
									{
										text:'申请部门：',
										style:'margin-left:10px;',
										width:60
									},{
										xtype:'textfield',
										name:'applyDepName',
										id:'applyDepName',
										width:100
									},
									{
										xtype : "hidden",
										name : "staffRecruitapply.dept.depId",
										id : "staffRecruitapply.dept.depId"
									},
									{
										text:'日期：',
										style:'margin-left:10px;',
										width:60
									},
									{
										xtype:'datefield',
										name:'staffRecruitapply.applyDate',
										id:'applyDate',
										width:100,
										format:'Y-m-d',
										value:new Date()
									}, {
										text : '招聘范围：',
										style : 'margin-left:5px;',
										width : 60
									}, {
										xtype : 'combo',
										name : 'staffRecruitapply.recruitArea',
										id : 'recruitArea',
										width : 100,
										triggerAction:'all',
										editable:false,
										allowBlank:false,
										mode:'local',
										store:['本部门招聘','公司招聘'],
										listeners:{
											beforeselect:function(combo,record,index){
												var sriResultGridData = Ext.getCmp('sriResultGridData').getValue();
												if (!Ext.isEmpty(sriResultGridData)) {//为空显示提示
													Ext.ux.Toast.msg('操作信息', '已经填写拟招岗位人员要求，不能更改招聘范围！');
													return false;
												}
												return true
											}
										}
									}
								]
								},{
								xtype: 'container',
								layout:'column',
								height:25,
								defaults:{
									xtype:'label',
									style:{
										margin:'0px 0px 3px 0px'
									}
								},
								items:[
									{
										text:'拟招岗位人员要求：'
									},{
										style:'color:red',
										id:'errorLabel',
										text:'(*必填)'
									}
								]}
								,{
								xtype : 'container',
								style : 'padding-left:0px;margin-bottom:10px',
								layout : 'column',
								items : [{
											name : 'sriResultGridData',
											xtype : 'hidden',
											id : 'sriResultGridData'
										},{
											name : 'sriDataList',
											xtype : 'hidden',
											id : 'sriDataList'
										},{
											xtype:'grid',
											id : 'sriResultGridDataGrid',
											height:220,
											width:'98%',
											stripeRows:true,
											trackMouseOver : true,
											clicksToEdit:1, 
											plugins:[new Ext.ux.grid.RowEditor({
												saveText: '保存',
												cancelText:'取消',
												errorText:'请输入完整信息',
												errorSummary:false
											})],
											store: new Ext.data.JsonStore({
												url : __ctxPath + '/statistics/listStaffRecruitInfo.do',
												root : 'result',
												totalProperty : 'totalCounts',
												remoteSort : true,
												fields : ['id',{name:'sriDepId',mapping:'dept.depId'},{name:'sriDepName',mapping:'dept.depName'},{name:'jobId',mapping:'job.jobId'},{name:'jobName',mapping:'job.jobName'},
														'needNum', 'sex',
														'age', 'needWorkDate', 'jobDesc',
														{name:'educationDicId',mapping:'educationDic.dicId'},{name:'educationDicName',mapping:'educationDic.itemValue'},
														'workYear', 'otherNeeds'],
												listeners:{
													'update':function(value){
														var r=this.getRange();								
														var resultArray = [];  
														var jsonArr =[];
														var sum=0;
														var rlen = r.length;  
														for (var i = 0; i < rlen; i++) { 
															resultArray.push([]);
															if (r[i].fields) {
															    var fields = r[i].fields;
															    var flen = fields.length;
															    var staffRecruitInfo =
																	{
																		dept : {
																			depId : ""
																		},
																		job : {
																			jobId:""
																		},
																		needNum:'',
																		age:'',
																		sex:'',
																		needWorkDate:'',
																		jobDesc:'',
																		educationDic: {
																			dicId:''
																		},
																		workYear:'',
																		otherNeeds:''
																	}
															    for (var z = 0; z < flen; z++) {
																	var fieldValue = r[i].get(fields.keys[z]);
																	if (Ext.isEmpty(fieldValue)||fieldValue == '请双击选择' || fieldValue == '请双击填写' ) {
																		continue;
																	}
																	if(fields.keys[z]=='id'){
																		if(fieldValue!=''){
																			staffRecruitInfo.id = fieldValue;
																		}
																	}else if (fields.keys[z] == 'sriDepId') {
																		resultArray[i].push('部门主键:' + fieldValue);
																		staffRecruitInfo.dept.depId = fieldValue;
																	} else if (fields.keys[z] == 'sriDepName') {
																		resultArray[i].push('部门:' + fieldValue);
																	}else if(fields.keys[z]=='jobId'){
																		staffRecruitInfo.job.jobId = fieldValue;
																	}else if(fields.keys[z]=='jobName'){
																		resultArray[i].push('拟招岗位:'+fieldValue); 
																	}else if(fields.keys[z]=='needNum'){
																		resultArray[i].push('需求人数:'+fieldValue); 
																		staffRecruitInfo.needNum = fieldValue;
																	}else if(fields.keys[z]=='sex'){
																		resultArray[i].push('性别要求:'+fieldValue); 
																		staffRecruitInfo.sex = fieldValue;
																	}else if(fields.keys[z]=='age'){
																		resultArray[i].push('年龄要求:'+fieldValue); 
																		staffRecruitInfo.age = fieldValue;
																	}else if(fields.keys[z]=='needWorkDate'){
																		if(fieldValue != ''){
																			resultArray[i].push('拟要求到岗日期:'+FormatGMTtoLocal(fieldValue,"yyyy-MM-dd")); 
																			staffRecruitInfo.needWorkDate = FormatGMTtoLocal(fieldValue,"yyyy-MM-dd");
																		}else{
																			resultArray[i].push('拟要求到岗日期:'+fieldValue); 
																			staffRecruitInfo.needWorkDate = fieldValue;
																		}
																	}else if(fields.keys[z]=='jobDesc'){
																		resultArray[i].push('岗位职责描述:'+fieldValue); 
																		staffRecruitInfo.jobDesc = fieldValue;
																	}else if(fields.keys[z]=='educationDicId'){
																		staffRecruitInfo.educationDic.dicId = fieldValue;
																	}else if(fields.keys[z]=='educationDicName'){
																		resultArray[i].push('学历要求:'+fieldValue); 
																	}else if(fields.keys[z]=='workYear'){
																		resultArray[i].push('工作经验要求:'+fieldValue); 
																		staffRecruitInfo.workYear = fieldValue;
																	}else if(fields.keys[z]=='otherNeeds'){
																		resultArray[i].push('其他特殊要求:'+fieldValue+';');
																		staffRecruitInfo.otherNeeds = fieldValue;
																	}
															    }
															    jsonArr.push(staffRecruitInfo);
															}
														}
														 //删除空元素
													    for(var i = 0; i < resultArray.length; i++){
													    	if(resultArray[i].length==0){
													    		resultArray.splice(i,1);
													    		i--;
													    	}
													    }
														Ext.getCmp('sriDataList').setValue(Ext.util.JSON.encode(jsonArr));
														Ext.getCmp('sriResultGridData').setValue(resultArray);
													}
											}
										}),
										cm:new Ext.grid.ColumnModel({
													columns : [new Ext.grid.RowNumberer(),{
														dataIndex : 'id',
														width:50,
														hidden:true
													}, {
														dataIndex : 'sriDepId',
														hidden : true,
														editor : new Ext.grid.GridEditor(new Ext.form.TextField({
															id : 'sriDepId',
															name : 'sriDepId'
														}))
													}, {
														header : '部门',
														dataIndex : 'sriDepName',
														width : 100,
														editor : new Ext.grid.GridEditor(new Ext.form.ComboBox({
															id : 'sriDepName',
															mode : "local",
															editable : false,
															allowBlank : false,
															valueField : "depName",
															displayField : "depName",
															triggerAction : "all",
															store : new Ext.data.JsonStore({
																root : "result",
																totalProperty : "totalCounts",
																url : __ctxPath + "/system/listDepDepartment.do",
																fields : ["depId", "depName"]
															}),
															listeners : {
																select : function(combo, record, index) {
																	var depId = record.data.depId;
																	var depName = record.data.depName;
																	Ext.getCmp("sriDepId").setValue(depId);
																	Ext.getCmp('sriJobName').setValue('');
																	Ext.getCmp('sriJobName').getStore().baseParams = {depId:depId};
																	Ext.getCmp('sriJobName').getStore().load();
																},
																afterrender:function(field){
																	var recruitArea = Ext.getCmp('recruitArea').getValue();
																	if(recruitArea=='本部门招聘'){
																		field.getStore().removeAll();
														  				field.setValue(__currentUserDept);
														  				Ext.getCmp('sriDepId').setValue(__currentUserDeptId);
														  				Ext.getCmp('sriJobName').setValue('');
														  				Ext.getCmp('sriJobName').getStore().baseParams = {depId:__currentUserDeptId};
																		Ext.getCmp('sriJobName').getStore().load();
																	}else if(recruitArea=='公司招聘'){
																		field.getStore().load();
																	}
																}
															}
														}))
													}
													,{
														dataIndex : 'jobId',
														hidden:true,
														editor:new Ext.grid.GridEditor(
																	new Ext.form.TextField({ 
																		id:'sriJobId',
																		name:'sriJobId'
								                        }))
													},{
														header : '拟招岗位',
														dataIndex : 'jobName',
														width:100,
														editor:new Ext.grid.GridEditor(
																	new Ext.form.ComboBox({
																		id:'sriJobName',
																		mode : "local",
																		editable : false,
																		allowBlank:false,
																		valueField : "jobName",
																		displayField : "jobName",
																		triggerAction : "all",
																		store : new Ext.data.SimpleStore({
																			url : __ctxPath
																					+ "/hrm/comboJob.do",
																			baseParams:{depId:__currentUserDeptId},
																			fields : [ "jobId", "jobName" ]
																		}),
																		listeners : {
																			select : function(combo,record,index){
																				var jobId = record.data.jobId;
																				var jobName = record.data.jobName;
																				Ext.getCmp("sriJobId").setValue(jobId);
																			},
																			focus:function(field){
																				var deptId  = Ext.getCmp('sriDepId').getValue();
																				if(Ext.isEmpty(deptId)){
																					Ext.ux.Toast.msg('操作信息', '请先选择部门再进行操作！');
																					return;
																				}
																			}
																		}
								                        }))
													}
													,{
														header : '需求人数',	
														dataIndex : 'needNum',
														width:100,
														editor:new Ext.grid.GridEditor(
																	new Ext.form.NumberField({ 
																		allowBlank: false,
																		blankText:'需求人数不能为空'
																		
								                        }))
													}
													,{
														header : '性别要求',	
														dataIndex : 'sex',
														width:100,
														editor:new Ext.grid.GridEditor(
																new Ext.form.ComboBox({
																		id:'sriSex',
																		mode : "local",
																		editable : false,
																		allowBlank:false,
																		triggerAction : "all",
																		store :['男','女','男女都可']
								                        }))
													},{
														header : '年龄要求',	
														dataIndex : 'age',
														width:100,
														editor:new Ext.grid.GridEditor(
																	new Ext.form.TextField({ 
																		id:'sriAge',
																		allowBlank: false,
																		blankText:'年龄要求不能为空'
																		
								                        }))
													},{
														header : '拟要求到岗日期',	
														dataIndex : 'needWorkDate',
														editor:new Ext.grid.GridEditor(
																new Ext.form.DateField({
																		allowBlank: false,
																		id:'sriNeedWorkDate',
																		format:'Y-m-d'
														})),
														renderer:function(value){
															if(value==''){
																return '';
															}else if(typeof value == "string"){
																return value;
															}else{
																return formatDate(value,'yyyy-MM-dd'); 
															}
														}
													},{
														header : '岗位职责描述',	
														dataIndex : 'jobDesc',
														editor:new Ext.grid.GridEditor(
																new Ext.form.TextField({
																		allowBlank: false,
																		id:'sriJobDesc'
														})),
														width:100
													},{
														dataIndex : 'educationDicId',
														hidden:true,
														editor:new Ext.grid.GridEditor(
																	new Ext.form.TextField({ 
																		id:'sriEducationDicId',
																		name:'sriEducationDicId',
																		readOnly:true
								                        }))
													},{
														header : '学历要求',	
														dataIndex : 'educationDicName',
														editor:new Ext.grid.GridEditor(
																new Ext.form.ComboBox({
																		allowBlank: false,
																		id:'sriEducationDicName',
																		mode:'local',
																		valueField : "itemValue",
																		displayField : "itemValue",
																		triggerAction : "all",
																		store : new Ext.data.JsonStore({
																			baseParams:{"Q_itemName_S_EQ":'学历'},
																			autoLoad:true,
																			root : "result",
																			totalProperty : "totalCounts",
																			url : __ctxPath
																					+ "/system/listDictionary.do",
																			fields : [ "dicId", "itemName","itemValue" ]
																		}),
																		editable:false,
																		allowBlank :false,
																		listeners : {
																			select : function(combo,record,index){
																				var dicId = record.data.dicId;
																				Ext.getCmp("sriEducationDicId").setValue(dicId);
																			}
																		}
														})),
														width:80
													},{
														header : '工作经验要求',	
														dataIndex : 'workYear',
														editor:new Ext.grid.GridEditor(
																	new Ext.form.TextField({
																		id:'sriWorkYear',
																		allowBlank :false,
																		maxLength:64
								                        }))
													},{
														header : '其他特殊要求',	
														dataIndex : 'otherNeeds',
														editor:new Ext.grid.GridEditor(
																	new Ext.form.TextField({
																		id:'sriOtherNeeds',
																		allowBlank :false,
																		maxLength:64
								                        }))
													}
													],
												defaults : {
													sortable : false,
													menuDisabled : false,
													width : 100
												}
											}),
											tbar :new Ext.Toolbar({
												height : 30,				
												items : [{
														iconCls : 'btn-add',
														text : '添加岗位人员要求',
														xtype : 'button',
														handler :function () {
															var recruitArea = Ext.getCmp('recruitArea').getValue();
															var deptId = "";
															var depName = "";
															if(Ext.isEmpty(recruitArea)){
																Ext.ux.Toast.msg('操作信息', '请先选择招聘范围再进行操作！');
																return;
															}
															if(recruitArea=='本部门招聘'){
												  				deptId = __currentUserDeptId;
												  				depName = __currentUserDept;
															}
															var DataRecord = Ext.data.Record.create([
																{name:'id'},{name:'sriDepId'},{name:'sriDepName'},{name:'jobId'},{name:'jobName'},{name:'needNum'},{name:'sex'},
															    {name:'age'},{name:'needWorkDate'},{name:'jobDesc'},{name:'educationDicId'},{name:'educationDicName'},
															    {name:'workYear'},{name:'otherNeeds'}
															    ]);
															var store =Ext.getCmp('sriResultGridDataGrid').store;
															var grid = Ext.getCmp('sriResultGridDataGrid'); 
																
																
															var n1 = ''; var n2 = '请双击选择';var n3 = '';var n4='';var n5 = '';var n8='';var n9='1';
	
															var newRowData = {
																			id:n1,sriDepId:deptId,sriDepName:depName,jobId:n1,jobName:n1,
																			needNum:n1,sex:n1,age:n1,needWorkDate:n1,
																			jobDesc:n1,educationDicId:n1,educationDicName:n1,workYear:n1,
																			otherNeeds:n1
																				}; 
															var newRecord = new DataRecord(newRowData); 
															store.add([newRecord]);
																
															grid.getSelectionModel().on('selectionchange', function(sm){  
														        Ext.getCmp('bookremoveBtn').setDisabled(sm.getCount() < 1);  
														    }); 
														}
													}
												, {
													iconCls : 'btn-del',
													text : '删除岗位人员要求',
													id:'bookremoveBtn',
													xtype : 'button',
													handler :function () {
														var store =Ext.getCmp('sriResultGridDataGrid').store;
														var grid = Ext.getCmp('sriResultGridDataGrid'); 
														var s = grid.getSelectionModel().getSelections();  
										                for(var i = 0, r; r = s[i]; i++){  
										                    store.remove(r);  
										                }
														store.fireEvent("update");//更新事件
													}
												}
												]
											})
										}]
							},{
								xtype : 'textfield',
								hidden : true,
								validator : function(){
								 	var sriResultGridData = Ext.getCmp('sriResultGridData').getValue();
									var errorLabel = Ext.getCmp("errorLabel");
			  	  		  			if(Ext.isEmpty(thizId)){
				  	  		  			if(Ext.isEmpty(sriResultGridData)){//为空显示提示
				  	  		  				errorLabel.setText('请填加岗位人员要求');
				  		  					return false;
				  	  		  			}
			  	  		  			}
			  	  		  			return true
								}
							}
							]
			});
		//加载表单对应的数据	
		if (this.id != null && this.id != 'undefined') {
			Ext.getCmp('sriResultGridDataGrid').getStore().load({params:{
					'Q_staffRecruitapply.id_L_EQ':this.id,
					start:0,
					limit:9999
			}});
			this.formPanel.getForm().load({
				deferredRender : false,
				url : __ctxPath + '/statistics/getStaffRecruitapply.do?id='+ this.id,
				waitMsg : '正在载入数据...',
				success : function(form, action) {
					var jsonData = Ext.util.JSON.decode(action.response.responseText);
					var res = jsonData.data;
					if(!Ext.isEmpty(res.dept)){
						Ext.getCmp("applyDepName").setValue(res.dept.depName);
						Ext.getCmp("applyDepName").originalValue=res.dept.depName;
						Ext.getCmp("staffRecruitapply.dept.depId").setValue(res.dept.depId);
						Ext.getCmp("staffRecruitapply.dept.depId").originalValue=res.dept.depId;
					}
					if(!Ext.isEmpty(res.applyUser)){
						Ext.getCmp("applyUserName").setValue(res.applyUser.fullname);
						Ext.getCmp("applyUserName").originalValue=res.applyUser.fullname;
						Ext.getCmp("staffRecruitapply.applyUser.userId").setValue(res.applyUser.userId);
						Ext.getCmp("staffRecruitapply.applyUser.userId").originalValue=res.applyUser.userId;
					}
				},
				failure : function(form, action) {
				}
			});
		}
		//初始化功能按钮
		this.buttons=[{
				text : '保存',
				iconCls : 'btn-save',
				handler :this.save.createCallback(this.formPanel,this)
			}, {
				text : '重置',
				iconCls : 'btn-reset',
				handler :this.reset.createCallback(this.formPanel)
			},{
				text : '取消',
				iconCls : 'btn-cancel',
				handler : this.cancel.createCallback(this)
			}];
	},//end of the initcomponents
	
	/**
	 * 重置
	 * @param {} formPanel
	 */
	reset:function(formPanel){
		formPanel.getForm().reset();
	},
	/**
	 * 取消
	 * @param {} window
	 */
	cancel:function(window){
		window.close();
	},
	/**
	 * 保存记录
	 */
	save:function(formPanel,window){
		if (formPanel.getForm().isValid()) {
			formPanel.getForm().submit({
				method : 'POST',
				waitMsg : '正在提交数据...',
				success : function(fp, action) {
					Ext.ux.Toast.msg('操作信息', '成功保存信息！');
					var gridPanel=Ext.getCmp('StaffRecruitapplyGrid');
					if(gridPanel!=null){
						gridPanel.getStore().reload();
					}
					window.close();
				},
				failure : function(fp, action) {
					Ext.MessageBox.show({
								title : '操作信息',
								msg : '信息保存出错，请联系管理员！',
								buttons : Ext.MessageBox.OK,
								icon : Ext.MessageBox.ERROR
							});
					window.close();
				}
			});
		}
	}//end of save
	
});